//
//  DetailDiseaseController.m
//  FastDoctor
//
//  Created by 李通 on 16/7/8.
//  Copyright © 2016年 sc. All rights reserved.
//

#import "DetailDiseaseController.h"
#import "DetailDiseaseDTO.h"
#import "SearchDTO.h"
#import "NSString+Pinyin.h"

@interface DetailDiseaseController ()

@property (nonatomic,strong) NSArray<DetailDiseaseDTO *> *diseaseList;

 //是否处于正在搜索状态
@property (nonatomic,assign,getter=isSearchState) BOOL searchState;

//提供给搜索的源数据
@property (nonatomic,strong) NSMutableArray *storeUserDTOList;
//搜索后的数据
@property (nonatomic,strong) NSMutableArray *searchUserDTOList;

@property (nonatomic,strong) UITextField *searchBar;

@property (nonatomic,strong) UILabel *noticeLabel;

@end

@implementation DetailDiseaseController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupBaseSetting];
    
    [DetailDiseaseDTO getDiseaseListSuccess:^(NSArray<DetailDiseaseDTO *> *diseaseList) {
        
        self.diseaseList = diseaseList;
        
        [SVProgressHUD dismiss];
    } error:^{
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textChanged:) name:UITextFieldTextDidChangeNotification object:nil];
}

 //基础界面设置
- (void)setupBaseSetting {
    
    self.navigationItem.titleView = self.searchBar;
    
    self.tableView.tableFooterView = [[UIView alloc]init];
}

#pragma mark - tableViewController delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    self.tableView.backgroundView = self.noticeLabel;
    
    if (self.isSearchState) {
        
        if (self.searchUserDTOList.count > 0) {
            
            self.noticeLabel.hidden = YES;
            
            return self.searchUserDTOList.count;
        }else {
            
            self.noticeLabel.hidden = NO;
            return 0;
        }
    }else {
        
        return self.storeUserDTOList.count;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (!cell) {
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
                                     reuseIdentifier:@"cell"];
    }
    SearchDTO *model;
    
    if (self.isSearchState) {
        
        model = self.searchUserDTOList[indexPath.row];
    }else {
        
        model = self.storeUserDTOList[indexPath.row];
    }
    
    cell.textLabel.text = model.diseaseName;
    
    return cell;
}


#pragma mark - 模糊搜索逻辑
- (void)textChanged:(NSNotification *)notification {
    
    UITextField *textField = (UITextField *)[notification object];
    //接收到通知开始搜索
    [self startSearchWithString:textField.text];
}

  //开始搜索
- (void)startSearchWithString:(NSString *)string {
    
    if (self.searchUserDTOList.count > 0) {
        //搜索之前移除数组内的所有数据,搜索后重新加载数据
        [self.searchUserDTOList removeAllObjects];
    }
    
    NSString *key = string.lowercaseString;
    
    NSMutableArray *mArray = [NSMutableArray array];
    
    /**
     *  从所有的数据里搜索相对应的字符串并将符合条件的字符串存入一个临时数组中
     */
    if (![key isEqualToString:@""] && ![key isEqual:[NSNull null]] && key != nil) {
        
        [self.storeUserDTOList enumerateObjectsUsingBlock:^(SearchDTO *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            NSString *diseaseName = obj.diseaseName.lowercaseString;
            NSString *pinyin = obj.pinyin.lowercaseString;
            NSString *firstLetter = obj.firstLetter.lowercaseString;
            
            NSRange range = [diseaseName rangeOfString:key];

            if (range.length > 0) {

                [mArray addObject:obj];
            }else {
                
                if ([firstLetter containsString:key]) {
                    
                    [mArray addObject:obj];
                }else {
                    
                    if ([firstLetter containsString:[key substringToIndex:1]]) {
                        
                        if ([pinyin containsString:key]) {
                            
                            [mArray addObject:obj];
                        }
                    }
                }
            }
        }];
           //遍历临时数组,再次判断临时数组内的数据将其添加到搜索结果数据中
        [mArray enumerateObjectsUsingBlock:^(SearchDTO *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if (![self.searchUserDTOList containsObject:obj]) {
                
                [self.searchUserDTOList addObject:obj];
            }
        }];
        self.searchState = YES;
    }
    //刷新数据
    [self.tableView reloadData];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [SVProgressHUD dismiss];
}

   //拿到数据后及时刷新tableView的显示
- (void)setDiseaseList:(NSArray *)diseaseList {
    
    _diseaseList = diseaseList;
    
    [self loadData];
}

 //当网络请求得到的数组有值时,对数据进行转换,储存到搜索源数组中
- (void)loadData {
    
    for (int i = 0 ; i < self.diseaseList.count; i++) {
        
        DetailDiseaseDTO *diseaseModel = self.diseaseList[i];
        
        NSString *pinyin = [diseaseModel.ci3_name transformToPinyin];
        NSString *firstLetter = [diseaseModel.ci3_name transformToPinyinFirstLetter];
        
        SearchDTO *model = [[SearchDTO alloc]init];
        model.diseaseName = diseaseModel.ci3_name;
        model.pinyin = pinyin;
        model.firstLetter = firstLetter;
        
        [self.storeUserDTOList addObject:model];
    }
    [self.tableView reloadData];
}

#pragma mark - 数据的传递
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *cellText = self.diseaseList[indexPath.row].ci3_name;
    
    if (self.block) {
        
        self.block(cellText);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 懒加载
- (UITextField *)searchBar {
    
    if (!_searchBar) {
        
        _searchBar = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 200, 30)];
        _searchBar.borderStyle = UITextBorderStyleRoundedRect;
        _searchBar.placeholder = @"请输入要查询的信息";
    }
    return _searchBar;
}

- (UILabel *)noticeLabel {
    
    if (!_noticeLabel) {
        
        _noticeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
        _noticeLabel.font = [UIFont systemFontOfSize:20];
        _noticeLabel.textColor = [UIColor lightGrayColor];
        _noticeLabel.textAlignment = NSTextAlignmentCenter;
        _noticeLabel.hidden = YES;
        _noticeLabel.text = @"抱歉！没有搜索到相关数据";
    }
    return _noticeLabel;
}

- (NSMutableArray *)searchUserDTOList {
    
    if (!_searchUserDTOList) {
        
        _searchUserDTOList = [NSMutableArray array];
    }
    return _searchUserDTOList;
    
}

- (NSMutableArray *)storeUserDTOList {
    
    if (!_storeUserDTOList) {
        
        _storeUserDTOList = [NSMutableArray array];
    }
    return _storeUserDTOList;
}

@end
